package ru.ifmo.trafficspy;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

import ru.ifmo.trafficspy.analyzer.learning.TrafficModelFactory;
import ru.ifmo.trafficspy.provider.Provider;
import ru.ifmo.trafficspy.provider.SimpleProvider;
import ru.ifmo.trafficspy.provider.TestProvider;

public class Learner {
	
	private void start() {
		Scanner in = new Scanner(System.in);
		ArrayList<Provider> providers = new ArrayList<Provider>();
		providers.add(new SimpleProvider(100, 10, 20));
		providers.add(new TestProvider());
		while (true) {
			System.out.println("traffic-spy by Fedor Tsarev & Dmitry Paraschenko, 2008");
			System.out.println("Learning mode");
			System.out.println("Enter the number of provider or q for quit");
			for (int i = 0; i < providers.size(); i++) {
				System.out.println(i + ". " + providers.get(i).getDescription());
			}
			String userInput = "";
			while (userInput == null || userInput.trim().equals("")) {
				if (userInput != null) {
					System.out.print("> ");
				}
				userInput = in.nextLine();
			}
			if ("q".equals(userInput)) {
				System.out.println("Bye!");
				break;
			}
			int choiceNumber = -1;
			try {
				choiceNumber = Integer.parseInt(userInput);
			} catch (NumberFormatException nfe) {
				System.out.println("Bad number");
				continue;
			}
			if (choiceNumber < 0 || choiceNumber >= providers.size()) {
				System.out.println("Bad number");
				continue;
			}
			String fname;
			String description;
			int stateCnt;
			int packetClustersCnt;
			int intervalClustersCnt;

			try {
				System.out.println("Enter filename for model: ");
				fname = in.nextLine();
				System.out.println("Enter description for model: ");
				description = in.nextLine();
				System.out.println("Enter number of states for model: ");
				stateCnt = in.nextInt();
				System.out.println("Enter number of clusters for packets: ");
				packetClustersCnt = in.nextInt();
				System.out.println("Enter number of clusters for intervals: ");
				intervalClustersCnt = in.nextInt();
			} catch (Exception e) {
				System.out.println("Bad format. Try again.");
				continue;
			}

			PrintWriter out;
			try {
				out = new PrintWriter(new FileWriter(fname));
			} catch (IOException e) {
				System.out.println("Cannot create file " + fname);
				continue;
			}
			description += ". Generated on " + System.currentTimeMillis();
			TrafficModelFactory.getTrafficModel(providers.get(choiceNumber).getTraffic(), packetClustersCnt, intervalClustersCnt, stateCnt, description).write(out);
			out.close();
			System.out.println("Model succesfully written to " + fname);
			System.out.println();
		}
	}
	
	public static void main(String[] args) {
		new Learner().start();
	}
}
